package soketWriter;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class WriteFromLink {
	
	
	
	
	
public static void main(String[] args) throws IOException {
	// create a TCP connection on port 80
	Socket socket=new Socket("185.31.17.193",80);
	
	// following HTTP/1.0 this is a simple get request
	String getRequest="GET /H1USigj.gif HTTP/1.1\r\nHost: i.imgur.com\r\nConnection: Close\r\n\r\n";
	
	// send the data of the HTTP/1.0 GET request over the wire
	OutputStream requestStream = socket.getOutputStream();	
	requestStream.write(getRequest.getBytes());
	
	// retrieve the response
	BufferedInputStream responseStream = new BufferedInputStream(socket.getInputStream());
	
	
	BufferedOutputStream write=new BufferedOutputStream(new FileOutputStream("image.gif"));
	int tmp = -1;
	
	char[] httpHeaderEnd = new char[] {'\r', '\n', '\r', '\n'};
	int httpHeaderCount = 0;
	
	ByteArrayOutputStream buffer = new ByteArrayOutputStream();
	
	while ((tmp = responseStream.read())>-1){
		if (tmp == httpHeaderEnd[httpHeaderCount]) {
			httpHeaderCount++;
			if (httpHeaderCount + 1 > httpHeaderEnd.length) {
				break;
			}
		} else {
			httpHeaderCount = 0;
		}
		buffer.write(tmp);
	}
	
	System.out.println("HTTP Header:" + new String(buffer.toByteArray()));
	
	int bytesRead = 0;
	
	while ((tmp = responseStream.read())>-1){
		bytesRead++;
		write.write(tmp);
		write.flush();
		//System.out.print(""+(char) tmp);
	}
	
	System.out.println(bytesRead);
	
	// close the connection (socket will be closed by the server!)
	write.close();
	requestStream.close();
	responseStream.close();
	socket.close();
	
}

}
